package com.yYclass.component;

import com.yYclass.config.SmsConfig;
import com.yYclass.util.CommonUtil;
import com.yYclass.util.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class SmsComponent {

    /**
     * 发送地址
     */
    private static final String HOST = "https://zwp.market.alicloudapi.com/sms/sendv2?mobile=%s&content=%s";
    @Autowired
    private SmsConfig smsConfig;

    @Autowired
    private RestTemplate restTemplate;

    @Async
    public void test(){
        log.info("<<<<<<<<<<<测试压力测试>>>>>>>>>>");
        try {
            Thread.sleep(3600);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 发送短信验证码
     * @param to
     * @param value
     */
    @Async("threadPoolTaskExecutor")
    public void send(String to,String value){

        String path = "/sms/sendv2";
        String method = "GET";
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "APPCODE " + smsConfig.getAppCode());
        Map<String, String> querys = new HashMap<>();
        querys.put("mobile", to);
        querys.put("content",value);
        HttpResponse response = null;
        try {
            response = HttpUtils.doGet(HOST, path, method, headers, querys);
            System.out.println(response.toString());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 发送短信的接口,最终的最新的，可以用的就是这个
     * @param to
     * @param templateId
     * @param content
     */
    @Async("threadPoolTaskExecutor")
    public void send(String to,String templateId,String content){
        long beginTime = CommonUtil.getCurrentTimestamp();

        String url = String.format(HOST,to,content);
        HttpHeaders headers = new HttpHeaders();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.set("Authorization","APPCODE "+smsConfig.getAppCode());
        HttpEntity entity = new HttpEntity<>(headers);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
        long endTime = CommonUtil.getCurrentTimestamp();
        log.info("耗时={},url={},body={}",endTime-beginTime,url,response.getBody());
        if(response.getStatusCode().is2xxSuccessful()){
            log.info("发送短信验证码成功");
        }else {
            log.error("发送短信验证码失败:{}",response.getBody());
        }
    }

    /**
     * 创建短信模板
     * @param content
     */
    public void createTemplate(String content){
        String host = "https://zwp.market.alicloudapi.com";
        String path = "/sms/edittemplete";
        String method = "POST";
        String appcode = "c5b4673214a0455f9d68461e70e6dcfe";
        Map<String, String> headers = new HashMap<>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<>();
        Map<String, String> bodys = new HashMap<>();
        bodys.put("content", "您的验证码如下，请勿泄露：#code#。");
        bodys.put("signature", "宥宥课堂");

        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);

            System.out.println("getStatusCode:" + response.getStatusLine().getStatusCode());
            String s = EntityUtils.toString(response.getEntity(), "UTF-8");
            System.out.println("s:" + s);
            //获取response的body
            //System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询当前短信的模板列表
     */
    public void getTemplateList(){
        long beginTime = CommonUtil.getCurrentTimestamp();

        String url = "https://zwp.market.alicloudapi.com/sms/tmplist";
        HttpHeaders headers = new HttpHeaders();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.set("Authorization","APPCODE "+smsConfig.getAppCode());
        HttpEntity entity = new HttpEntity<>(headers);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);

        long endTime = CommonUtil.getCurrentTimestamp();

        log.info("耗时={},url={},body={}",endTime-beginTime,url,response.getBody());
        if(response.getStatusCode().is2xxSuccessful()){
            log.info("正常返回模板列表");
        }else {
            log.error("返回模板失败:{}",response.getBody());
        }
    }
}
